package com.xunshibao.tutor.user.dao;


import java.util.Date;

import org.springframework.stereotype.Repository;

import com.xunshibao.core.dao.BaseDAO;
import com.xunshibao.core.page.Pagination;
import com.xunshibao.tutor.po.User;

@Repository
public class UserDaoImpl {
    /**
     * 根据用户名取得用户的id, uname, pwd信息
     * 
     * @param username
     *            用户名
     * @return
     */
    public User login(String username) {
        String sql = "select id, uname, pwd from w_user where uname=?";
        return BaseDAO.queryForObject(User.class, sql, new Object[]{username});
    }
    
    public String validUsername(String username) {
        String sql = "select uname from w_user where uname=?";
        return (String) BaseDAO.queryOneRowOneCol(sql, new Object[]{username});
        
    }

    public int updateLogin(Long uid, String ip, Date lastDate) {
        String sql = "update w_user set lastdt=?,ip=?,times=times+1 where id=?";
        return BaseDAO.execute(sql, new Object[] { lastDate, ip, uid });
    }
    
    public int changePassword(Integer uid, String newpassword){
        String sql = "update w_user set pwd=? where id=?";
        return BaseDAO.execute(sql, new Object[]{newpassword, uid});
    }
    
    public int regUser(String uname, String password, String ip, Date regDate) {
        String sql = "insert into w_user(uname, pwd, ip, regdt, lastdt, times, points) values(?,?,?,?,?,0,0)";
        return BaseDAO.execute(sql, new Object[]{uname, password, ip, regDate, regDate});
    }
    
    public Pagination listUser(Integer pageNo, Integer pageSize, String orderField, boolean desc) {
        String sql = "select uname, lastdt, ip from w_user order by {0} {1}";
        if(orderField != null && !"".equals(orderField)) {
            sql = sql.replace("{0}", orderField);
            if(desc) {
                sql = sql.replace("{1}", "desc");
            } else {
                sql = sql.replace("{1}", "asc");
            }
        }
        return BaseDAO.page(User.class, sql, new Object[]{}, pageNo, pageSize);
    }
}
